package com.project.services;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import com.project.utility.DownloadTask;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

public class ServiceDownload extends Service{

	
	@Override
	public IBinder onBind(Intent intent) {
		return new MyBinder();
	}
	
	
	@Override
	public void onCreate(){
		Log.i("t", "test");
	}
	
	@Override
	public void onStart(Intent intent,int startId){
		
	}
	
	@Override
	public boolean onUnbind(Intent intent){ 
        return super.onUnbind(intent);   
	}
	
	public void onDestroy() {  
		super.onDestroy();
    }
	
	private static class DownloadTaskThread extends Thread 
	{
		private DownloadTask task;
		public DownloadTaskThread(DownloadTask task){
			this.task = task;
		}
		
		@Override
		public void run(){
			
				String finalUrl=task.getUrl();
				try {
					HttpURLConnection con;
					con = (HttpURLConnection)(new URL( task.getUrl() ).openConnection());
					con.setInstanceFollowRedirects( false );
					con.connect();
					String location = con.getHeaderField( "Location" );
					if(location!=null&&location.length()>0)
						finalUrl = location;
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			try {
				URL url = new URL(finalUrl);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.connect();
				String fileName = task.getFileName();
				InputStream input = new BufferedInputStream(url.openStream());
				boolean externalAvailable = false;
				boolean externalWriteable = false;
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					// HERE MEDIA IS BOTH AVAILABLE AND WRITEABLE
					externalAvailable = true;
					externalWriteable = true;
				} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
					// HERE SD CARD IS AVAILABLE BUT NOT WRITEABLE
					externalAvailable = true;
				}
				if (!externalAvailable || !externalWriteable)
					return;
				task.setContentLength(connection.getContentLength());
				task.setFileName(fileName);
				
				File file = new File(task.getTargetLocation(), fileName);
				file.getParentFile().mkdirs();
				file.createNewFile();
				FileOutputStream output = new FileOutputStream(file);
				byte data[] = new byte[1024];
				int count = 0;
				int sum = 0;
				while ((count = input.read(data))>0) {
					output.write(data, 0, count);
					sum+=count;
					task.setCurrent(sum);
				}
				output.flush();
				output.close();
				input.close();
				task.setFinished(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private static class MyBinder extends Binder implements IServiceDownload{
		private static List<DownloadTask> taskCollection=new ArrayList<DownloadTask>();
		public MyBinder(){
			
		}

		@Override
		public void download(DownloadTask task) {
			for (DownloadTask taskItem : taskCollection)
				if(taskItem.getUrl().equals(task.getUrl()))
						return;
			taskCollection.add(task);
			DownloadTaskThread taskThread = new DownloadTaskThread(task);
			taskThread.start();
		}

		@Override
		public List<DownloadTask> getProcess() {
			return taskCollection;
		}
	}

}
